#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/02/12
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from flask import Blueprint, request, json, url_for, redirect, session, abort
from flask_login import LoginManager, login_required, login_user, logout_user, current_user
from project import app
from project.define import page_logger, AxiosMessage
from project.modules import User, AnonymousUser, ChargeClasses


# 认证
auth = Blueprint(name='auth', import_name='project', url_prefix='/auth', template_folder='routes/templates')
RouterName = "auth"
# 认证管理
auth_manager = LoginManager(app)
auth_manager.login_view = "index.default"
auth_manager.anonymous_user = AnonymousUser

# 页面消息
PageMessage = AxiosMessage()


@auth_manager.user_loader
def load_user(user_id):
    """
    登录验证
    """
    return User.query.get(int(user_id))


@auth.route('/auth_user', methods=['POST'])
def auth_user():
    """
    用户认证
    """
    view = "auth_user"
    try:
        # 检查数据类型
        p_data = request.get_json()
        if not isinstance(p_data, dict):
            p_data = json.loads(p_data)
        page_logger.debug(f"{RouterName}.{view} => 接口数据：{p_data}")
        auth_info = p_data.get('AuthInfo')
        if auth_info:
            login_name = auth_info['LoginName']
            password = auth_info['Password']
            remember = auth_info['Remember']
            u = User.query.filter_by(LoginName=login_name).first()
            if u:
                if u.verify_password(password):
                    if u.Active:
                        login_user(u, remember)
                        page_logger.debug(f"{RouterName}.{view} => 用户登录成功：{login_name}")
                        next = request.args.get('next')
                        if next is None or next.startswith("/"):
                            # 默认登录重定向
                            next = url_for("charge.default")
                        c = ChargeClasses.cashier_charge_class(**u.to_dict())
                        if c:
                            session['ClassesID'] = c['ClassesID']
                            charge_info = dict.fromkeys(["ClassesID","CashierName","UserName"])
                            charge_info.update(**c)
                            page_logger.debug(f"收费信息 => {charge_info}")
                        return PageMessage.json_data(**{'icon': 'success', 'text': '登入成功','redirect': next})
                    else:
                        return PageMessage.warning("用戶已停用")
                else:
                    return PageMessage.error("密碼錯誤")
            else:
                return PageMessage.error("用戶不存在")
    except Exception as e:
        page_logger.error(f"{RouterName}.{view} => 参数接口调用失败：{e}")
    return abort(500)


@auth.route('/logout')
@login_required
def logout():
    """
    登出
    """
    view = "logout"
    page_logger.debug(f"{RouterName}.{view} => 用户登出系统：{current_user.LoginName}")
    logout_user()
    return redirect(url_for('index.default'))
